<template>
  <el-dialog
    v-model="dialogVisible"
    title="制度详情"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="system-detail" v-loading="loading">
      <!-- 基本信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
            <div class="header-actions">
              <el-tag :type="getStatusTagType(systemData.status)" size="large">
                {{ getStatusText(systemData.status) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>制度名称：</label>
              <span>{{ systemData.name }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>制度编号：</label>
              <span>{{ systemData.code }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>制度类型：</label>
              <el-tag :type="getTypeTagType(systemData.type)" size="small">
                {{ getTypeText(systemData.type) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>版本号：</label>
              <span>{{ systemData.version }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>归属部门：</label>
              <span>{{ systemData.department }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>制定人：</label>
              <span>{{ systemData.creator }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>生效日期：</label>
              <span>{{ systemData.effectiveDate || '未设置' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>失效日期：</label>
              <span>{{ systemData.expiryDate || '未设置' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ systemData.createTime }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>最后更新：</label>
              <span>{{ systemData.updateTime || systemData.createTime }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 制度内容 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <span class="card-title">制度描述</span>
        </template>
        <div class="content-section">
          <p>{{ systemData.description || '暂无描述' }}</p>
        </div>
      </el-card>

      <!-- 详细内容 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">制度内容</span>
            <div class="header-actions">
              <el-button size="small" @click="handlePreview">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button size="small" @click="handleExport">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </div>
        </template>
        <div class="content-section">
          <div class="content-text" v-html="formatContent(systemData.content)"></div>
        </div>
      </el-card>

      <!-- 关键词 -->
      <el-card class="detail-card" shadow="never" v-if="systemData.keywords && systemData.keywords.length">
        <template #header>
          <span class="card-title">关键词</span>
        </template>
        <div class="keywords-section">
          <el-tag
            v-for="keyword in systemData.keywords"
            :key="keyword"
            size="small"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ keyword }}
          </el-tag>
        </div>
      </el-card>

      <!-- 附件信息 -->
      <el-card class="detail-card" shadow="never" v-if="attachments.length">
        <template #header>
          <span class="card-title">相关附件</span>
        </template>
        <div class="attachments-section">
          <div
            v-for="file in attachments"
            :key="file.id"
            class="attachment-item"
          >
            <div class="attachment-info">
              <el-icon class="attachment-icon"><Document /></el-icon>
              <div class="attachment-details">
                <div class="attachment-name">{{ file.name }}</div>
                <div class="attachment-meta">
                  {{ formatFileSize(file.size) }} | {{ file.uploadTime }}
                </div>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button size="small" link @click="handlePreviewFile(file)">
                预览
              </el-button>
              <el-button size="small" link @click="handleDownloadFile(file)">
                下载
              </el-button>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 版本历史 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">版本历史</span>
            <div class="header-actions">
              <el-button size="small" @click="handleVersionHistory">
                查看全部
              </el-button>
            </div>
          </div>
        </template>
        <div class="version-section">
          <el-timeline>
            <el-timeline-item
              v-for="version in versionHistory"
              :key="version.id"
              :timestamp="version.createTime"
              placement="top"
            >
              <div class="version-item">
                <div class="version-header">
                  <span class="version-number">{{ version.version }}</span>
                  <el-tag
                    :type="version.status === 'active' ? 'success' : 'info'"
                    size="small"
                  >
                    {{ getStatusText(version.status) }}
                  </el-tag>
                </div>
                <div class="version-content">
                  <p>{{ version.description }}</p>
                  <div class="version-meta">
                    <span>创建人：{{ version.creator }}</span>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>

      <!-- 操作记录 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <span class="card-title">操作记录</span>
        </template>
        <div class="operation-section">
          <el-table :data="operationLogs" style="width: 100%">
            <el-table-column prop="operation" label="操作类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getOperationTagType(row.operation)" size="small">
                  {{ getOperationText(row.operation) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="100" />
            <el-table-column prop="operationTime" label="操作时间" width="160" />
            <el-table-column prop="description" label="操作描述" show-overflow-tooltip />
          </el-table>
        </div>
      </el-card>

      <!-- 备注信息 -->
      <el-card class="detail-card" shadow="never" v-if="systemData.remark">
        <template #header>
          <span class="card-title">备注信息</span>
        </template>
        <div class="content-section">
          <p>{{ systemData.remark }}</p>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
        <el-button type="success" @click="handleCopy">
          <el-icon><CopyDocument /></el-icon>
          复制
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  View,
  Download,
  Document,
  Edit,
  CopyDocument
} from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  systemData?: any
}

const props = withDefaults(defineProps<Props>(), {
  systemData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'edit'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加载状态
const loading = ref(false)

// 附件列表
const attachments = ref([
  {
    id: 1,
    name: '水库安全管理制度.docx',
    size: 1024000,
    uploadTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '安全检查表.xlsx',
    size: 512000,
    uploadTime: '2024-01-01 10:30:00'
  }
])

// 版本历史
const versionHistory = ref([
  {
    id: 1,
    version: 'V2.1',
    status: 'active',
    description: '更新安全检查流程，增加应急处理程序',
    creator: '张三',
    createTime: '2024-01-01 09:00:00'
  },
  {
    id: 2,
    version: 'V2.0',
    status: 'archived',
    description: '重构制度框架，优化管理流程',
    creator: '李四',
    createTime: '2023-06-01 14:30:00'
  },
  {
    id: 3,
    version: 'V1.0',
    status: 'archived',
    description: '初始版本',
    creator: '王五',
    createTime: '2023-01-01 08:00:00'
  }
])

// 操作记录
const operationLogs = ref([
  {
    operation: 'create',
    operator: '张三',
    operationTime: '2024-01-01 09:00:00',
    description: '创建制度'
  },
  {
    operation: 'update',
    operator: '李四',
    operationTime: '2024-01-15 10:30:00',
    description: '更新制度内容'
  },
  {
    operation: 'publish',
    operator: '王五',
    operationTime: '2024-01-20 14:00:00',
    description: '发布制度'
  }
])

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    management: 'primary',
    technical: 'success',
    operation: 'warning',
    safety: 'danger',
    quality: 'info'
  }
  return types[type] || 'primary'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    management: '管理制度',
    technical: '技术规范',
    operation: '操作规程',
    safety: '安全制度',
    quality: '质量标准'
  }
  return texts[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const types: Record<string, string> = {
    active: 'success',
    draft: 'info',
    expired: 'warning',
    abolished: 'danger',
    archived: ''
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    active: '生效中',
    draft: '草稿',
    expired: '已过期',
    abolished: '已废止',
    archived: '已归档'
  }
  return texts[status] || status
}

// 获取操作标签类型
const getOperationTagType = (operation: string) => {
  const types: Record<string, string> = {
    create: 'success',
    update: 'primary',
    publish: 'warning',
    abolish: 'danger',
    archive: 'info'
  }
  return types[operation] || 'info'
}

// 获取操作文本
const getOperationText = (operation: string) => {
  const texts: Record<string, string> = {
    create: '创建',
    update: '更新',
    publish: '发布',
    abolish: '废止',
    archive: '归档'
  }
  return texts[operation] || operation
}

// 格式化内容
const formatContent = (content: string) => {
  if (!content) return '暂无内容'
  return content.replace(/\n/g, '<br>')
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  return (size / (1024 * 1024)).toFixed(1) + ' MB'
}

// 预览制度
const handlePreview = () => {
  ElMessage.info('预览功能开发中...')
}

// 导出制度
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 预览文件
const handlePreviewFile = (file: any) => {
  ElMessage.info(`预览文件：${file.name}`)
}

// 下载文件
const handleDownloadFile = (file: any) => {
  ElMessage.success(`下载文件：${file.name}`)
}

// 查看版本历史
const handleVersionHistory = () => {
  ElMessage.info('版本历史功能开发中...')
}

// 编辑制度
const handleEdit = () => {
  emit('edit', props.systemData)
  handleClose()
}

// 复制制度
const handleCopy = () => {
  const copyData = {
    ...props.systemData,
    id: undefined,
    name: props.systemData.name + ' - 副本',
    code: '',
    status: 'draft'
  }
  emit('edit', copyData)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.system-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.detail-item span {
  color: #303133;
}

.content-section {
  padding: 10px 0;
}

.content-text {
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
}

.keywords-section {
  padding: 10px 0;
}

.attachments-section {
  padding: 10px 0;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
}

.attachment-item:last-child {
  margin-bottom: 0;
}

.attachment-info {
  display: flex;
  align-items: center;
}

.attachment-icon {
  font-size: 24px;
  color: #409eff;
  margin-right: 12px;
}

.attachment-details {
  flex: 1;
}

.attachment-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.attachment-meta {
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 8px;
}

.version-section {
  padding: 10px 0;
}

.version-item {
  padding-left: 10px;
}

.version-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.version-number {
  font-weight: 600;
  color: #303133;
}

.version-content p {
  margin: 0 0 8px 0;
  color: #606266;
}

.version-meta {
  font-size: 12px;
  color: #909399;
}

.operation-section {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}
</style>